How To Create JavaScript onclick  ON-OFF Switch Button Using HTML CSS and JavaScript

How To Create JavaScript onclick ON-OFF Switch Button Using HTML CSS and JavaScript

Suraj (UI/UX Developer)
Jul 2024

Modern websites focus on interactive and user-friendly UI elements, and one of the most commonly used components is an ON-OFF toggle switch. These switches are widely used for settings like dark mode, notifications, Wi-Fi, or feature enable/disable options.

In this tutorial, you’ll learn how to create a JavaScript onclick ON-OFF switch button using HTML, CSS, and JavaScript step by step. No libraries or frameworks are required—just pure frontend code.

Why Use an ON-OFF Switch Button?

An ON-OFF switch improves user experience by:

Making actions visually clear

Replacing boring checkboxes

Providing instant feedback

Working smoothly on desktop and mobile devices

Using JavaScript, we can easily detect the switch state and perform actions dynamically.

How This JavaScript ON-OFF Switch Works

The onclick event triggers the toggleButton() function

JavaScript adds or removes the active class

CSS handles the animation and color change

Text updates dynamically based on switch state

This approach keeps the code clean, readable, and beginner-friendly.

Real-World Use Cases

You can use this ON-OFF switch for:

Dark mode toggle

Sound ON/OFF

Feature enable/disable

User settings panel

Admin dashboards

You can also connect this switch to APIs, databases, or local Storage for advanced functionality.

Final Thoughts

Creating a JavaScript onclick ON-OFF switch button using HTML, CSS, and JavaScript is simple yet powerful. With minimal code, you can build interactive UI components that enhance user experience and website usability.

This switch design is fully customizable—you can change colors, size, animations, or even add icons based on your project needs.

HTML

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How To Create JavaScript onclick ON-OFF Switch Button Using HTML CSS and JavaScript</title>

</head>

<body>

<img id="clickimage" src="image/off.jpg" style="width:200px">

<!-- start on click btn -->

<button onclick="document.getElementById('clickimage').src='image/on.jpg'" class="on">ON</button>

<button onclick="document.getElementById('clickimage').src='image/off.jpg'" class="off">OFF</button>

</body>

</html>

CSS

body{margin: auto;display: flex;text-align: center;}

.on{padding: 5px 20px; background: #00a61d; color: #fff;border: 2px solid #ccc;font-size: 16px;border-radius: 0px;}

.off{padding: 5px 20px; background: #ff5d7d; color: #fff;border: 2px solid #ccc;font-size: 16px;border-radius: 0px;}